package com.fanx.sample.web.common;

import org.apache.commons.lang3.math.NumberUtils;
import org.springframework.core.MethodParameter;
import org.springframework.web.bind.support.WebDataBinderFactory;
import org.springframework.web.context.request.NativeWebRequest;
import org.springframework.web.method.support.HandlerMethodArgumentResolver;
import org.springframework.web.method.support.ModelAndViewContainer;

import lombok.extern.slf4j.Slf4j;

@Slf4j
//@Component
public class JwtMethodArgumentResolver implements HandlerMethodArgumentResolver {

    @Override
    public boolean supportsParameter(MethodParameter parameter) {
        return parameter.hasParameterAnnotation(JwtUserId.class);
    }
    
    @Override
    public Object resolveArgument(MethodParameter parameter, ModelAndViewContainer mavContainer,
            NativeWebRequest webRequest, WebDataBinderFactory binderFactory) throws Exception {
        parameter.getParameterType().isInstance(Long.class);
        String userId = webRequest.getHeader("jwt-userId");
        log.info("method: {}, jwt-userId: {}", parameter.getMethod().getName(), userId);
        if (NumberUtils.isDigits(userId)) {
            return Long.valueOf(userId);
        }
        throw new Exception("未授权异常");
    }
}
